package cn.jjxx.modules.iface.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.ServletUtils;
import cn.jjxx.core.utils.SpringContextHolder;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.activiti.controller.WorkFlowController;
import cn.jjxx.modules.activiti.service.IFlowService;
import cn.jjxx.modules.activiti.workflow.BillBean;
import cn.jjxx.modules.activiti.workflow.Config;
import cn.jjxx.modules.activiti.workflow.OperateBean;
import cn.jjxx.modules.map.service.ICommonMapService;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.service.IUserService;
import cn.jjxx.modules.sys.utils.UserUtils;
import cn.jjxx.modules.workflow.entity.HisTask;
import cn.jjxx.modules.workflow.entity.Task;
import cn.jjxx.modules.workflow.service.IHisTaskService;
import cn.jjxx.modules.workflow.service.ITaskService;

@Controller
@RequestMapping("/iface/activiti")
@Api(tags = "流程接口",description="流程接口管理文档",hidden=true)
public class ActivitiIfaceController {
	
	/**办理任务跳转地址*/
	private static String taskUrl = "admin/activiti/flow/flowAudit?taskId=";
	/**计量流程办理跳转地址*/
	private static String meterTaskUrl = "admin/meter/billreview/{billId}/taskinfo";
	/**签收任务跳转地址*/
	private static String signUrl = "admin/activiti/flow/personal/needDisposeTask";

	@Autowired
    protected ICommonMapService commonMapService;
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected ITaskService taskService;
	@Autowired
	protected IHisTaskService hisTaskService;
	@Autowired
	protected IUserService userService;
	@Autowired
	protected IFlowService flowService;

	@RequestMapping(value="/getMyTasks",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="获取用户流程",notes="获取用户流程，提供给统一用户平台使用")
	@ApiImplicitParams({
		@ApiImplicitParam(name="username",value="用户名",dataType="String",required=true, paramType = "query")
	})
	@ApiResponse(response=List.class, code = 200, message = "接口返回对象参数")
	public List<Map<String,Object>> getMyTasks(HttpServletRequest request, String username){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		//获取用户
		EntityWrapper<User> uwrapper = new EntityWrapper<User>(User.class);
		uwrapper.eq("username", username);
		User user = userService.selectOne(uwrapper);
		if(!ObjectUtils.isNullOrEmpty(user)){
			EntityWrapper<Task> wrapper = new EntityWrapper<Task>(Task.class);
			wrapper.eq("assignee", user.getId());
			wrapper.or("signer = '"+user.getId()+"'");
			List<Task> tasks = taskService.selectList(wrapper, true);
			//获取系统名称和系统基础路径
			//获取正在运行的变量
			for(Task task:tasks){
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("taskId", task.getId());
				BillBean billBean = runtimeService.getVariable(task.getExecutionId(), Config.variable.表单信息.toString(), BillBean.class);
				map.put("orgName", "");
				map.put("procInsId", task.getProcInstId());
				map.put("procDefId", task.getProcDefId());
				map.put("taskDefId", task.getTaskDefKey());
				map.put("dealType", task.getSigner());
				map.put("url", taskUrl+task.getId());
				if(task.getTreatmentType().equals(String.valueOf(1))){
					map.put("url", signUrl);
				}else{
					if(task.getFlowName().contains("计量")||task.getFlowType().contains("计量")){
						meterTaskUrl = meterTaskUrl.replace("{billId}", task.getBusinessKey());
						map.put("url", meterTaskUrl);
					}
				}
				list.add(map);
			}
		}
		return list;
	}
	
	/**
	 * @Description: 获取我的任务，按照时间倒序排序 .<br>
	 * @param pages 页数.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-11-20 下午2:33:44.<br>
	 */
	@RequestMapping(value="/getMyTaskList",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="我的待办任务",notes="分页获取我的待办任务")
	@ApiImplicitParams({
		@ApiImplicitParam(name="page",value="页数",dataType="Long",required=true,defaultValue="0", paramType = "query"),
		@ApiImplicitParam(name="size",value="显示条数",dataType="Long",required=true,defaultValue="10", paramType = "query")
	})
	@ApiResponse(response=AjaxJson.class, code = 200, message = "接口返回对象参数")
	public AjaxJson getMyTaskList(Queryable queryable,Pages pages){
		AjaxJson j = new AjaxJson();
		EntityWrapper<Task> entityWrapper = new EntityWrapper<Task>(Task.class);
		entityWrapper.eq("assignee", UserUtils.getUser().getId());
    	entityWrapper.or("signer = '"+UserUtils.getUser().getId()+"'");
		entityWrapper.orderBy("create_time_",false);
        com.baomidou.mybatisplus.plugins.Page<Task> page = new com.baomidou.mybatisplus.plugins.Page<Task>(pages.getPage()+1, pages.getSize());
        com.baomidou.mybatisplus.plugins.Page<Task> pageList =  taskService.selectPage(page, entityWrapper,true);
        if(pageList.getRecords().size()>0){
        	j.setData(pageList.getRecords());
        }else{
        	j.setRet(AjaxJson.RET_FAIL);
        }
        return j;
	}
	
	/**
	 * @Description: 获取我的已办任务，按时间倒序排序 .<br>
	 * @param pages 页数.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-11-20 下午2:37:48.<br>
	 */
	@RequestMapping(value="/getMyHisTaskList",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="我的已办任务",notes="分页获取我的已办任务，按时间倒序排序")
	@ApiImplicitParams({
		@ApiImplicitParam(name="page",value="页数",dataType="Long",required=true,defaultValue="0", paramType = "query"),
		@ApiImplicitParam(name="size",value="显示条数",dataType="Long",required=true,defaultValue="10", paramType = "query")
	})
	@ApiResponse(response=AjaxJson.class, code = 200, message = "接口返回对象参数")
	public AjaxJson getMyHisTaskList(Queryable queryable,Pages pages){
		AjaxJson j = new AjaxJson();
		EntityWrapper<HisTask> entityWrapper = new EntityWrapper<HisTask>(HisTask.class);
		entityWrapper.orderBy("endTime", false);
		entityWrapper.eq("assignee", UserUtils.getUser().getId());
		com.baomidou.mybatisplus.plugins.Page<HisTask> page = new com.baomidou.mybatisplus.plugins.Page<HisTask>(pages.getPage()+1, pages.getSize());
		com.baomidou.mybatisplus.plugins.Page<HisTask> list = hisTaskService.selectPage(page, entityWrapper);
		if(list.getRecords().size()>0){
        	j.setData(list.getRecords());
        }else{
        	j.setRet(AjaxJson.RET_FAIL);
        }
		return j;
	}
	
	/**
	 * @Description: 手机端提交流程 .<br>
	 * @param request http请求.<br>
	 * @param response http响应.<br>
	 * @param billBean 单据配置实体.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-11-12 上午11:06:47.<br>
	 */
	@RequestMapping(value="/submitBill",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="提交流程",notes="手机端提交流程")
	@ApiImplicitParams({
		@ApiImplicitParam(name="billId",value="单据Id",dataType="String", required=true, paramType = "query"),
		@ApiImplicitParam(name="menuId",value="菜单Id",dataType="String", required=true, paramType = "query")
	})
	@ApiResponse(response=AjaxJson.class, code = 200, message = "接口返回对象参数")
	public AjaxJson submitBill(HttpServletRequest request,HttpServletResponse response,BillBean billBean){
		AjaxJson j = new AjaxJson();
		j = SpringContextHolder.getBean(WorkFlowController.class).submitFlow(request, response, billBean);
		return j;
	}
	
	/**
	 * @Description: 手机端审批流程接口 .<br>
	 * @param request http请求.<br>
	 * @param response http响应.<br>
	 * @param taskId 任务Id.<br>
	 * @param operate 处理实体类.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-11-12 上午11:07:31.<br>
	 */
	@RequestMapping(value="/complateTask",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="审批流程",notes="手机端审批流程接口")
	@ApiImplicitParams({
		@ApiImplicitParam(name="taskId",value="任务Id",dataType="String",required=true, paramType = "query"),
		@ApiImplicitParam(name="policy",value="决策(0:通过,1：打回)",dataType="int",defaultValue="0",allowableValues="0,1", paramType = "query"),
		@ApiImplicitParam(name="opinion",value="审批意见",dataType="String",required=true, paramType = "query"),
	})
	@ApiResponse(response=AjaxJson.class, code = 200, message = "接口返回对象参数")
	public AjaxJson complateTask(HttpServletRequest request,HttpServletResponse response,String taskId,OperateBean operate){
		AjaxJson j = new AjaxJson();
		j = SpringContextHolder.getBean(WorkFlowController.class).completeTask(request, response, taskId, operate);
		return j;
	}
	
	/**
	 * @Description: 获取历史任务流程，按时间排序 .<br>
	 * @param billId 单据Id.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-11-26 下午2:09:36.<br>
	 */
	@RequestMapping(value="/getHisTasksByBillId",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="获取单据历史流程",notes="根据单据Id,获取历史流程")
	@ApiImplicitParams({
		@ApiImplicitParam(name="billId",value="单据Id",dataType="String",required=true, paramType = "query"),
	})
	@ApiResponse(response=AjaxJson.class, code = 200, message = "接口返回对象参数")
	public AjaxJson getHisTasksByBillId(String billId){
		AjaxJson j = new AjaxJson();
		List<HistoricTaskInstanceEntity> hisTasks= flowService.findHisTask(billId);
		j.setData(hisTasks);
		return j;
	}
	
	/**
	 * @Description: 获取App表单地址 .<br>
	 * @param billId 单据Id.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-11-26 下午2:09:36.<br>
	 */
	@RequestMapping(value="/getAppFormUrl",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="获取APP表单地址",notes="获取App表单地址")
	@ApiImplicitParams({
		@ApiImplicitParam(name="taskId",value="任务Id",required=true,dataType="String", paramType = "query"),
	})
	@ApiResponse(response=AjaxJson.class, code = 200, message = "接口返回对象参数")
	public AjaxJson getAppFormUrl(String taskId){
		AjaxJson j = new AjaxJson();
		String appFormUrl = null;
		String projectName = ServletUtils.getRequest().getServletContext().getContextPath();
		BillBean billInfo = flowService.getBillBeanByTaskId(taskId);
		if(billInfo!=null&&StringUtils.isNotEmpty(billInfo.getAppFormUrl())){
			appFormUrl = projectName + "/"+billInfo.getAppFormUrl();
			j.setData(appFormUrl);
		}else{
			j.setRet(AjaxJson.RET_FAIL);
		}
		return j;
	}
	
	@RequestMapping(value="/getProcessInstance",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="获取流程实例信息",notes="获取流程实例信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name="proInstId",value="流程实例Id",required=true,dataType="String", paramType = "query"),
	})
	@ApiResponse(response=AjaxJson.class, code = 200, message = "接口返回对象参数")
	public AjaxJson getProcessInstance(String proInstId){
		AjaxJson j = new AjaxJson();
		HistoricProcessInstance proInst = flowService.getHistoricProcessInstance(proInstId);
		j.setData(proInst);
		return j;
	}
}
